This 5-part article is intended as an introduction to BASIC programming. It was originally published in the Boston Computer Society's PC Report magazine in May-September 1992. I am also the author of the "QuickBASIC and QBASIC Quick Reference Guide", published by DDC Publishing. This Quick Reference is designed to help you find QuickBASIC and QBASIC information fast. It shows how to use all the features of the QuickBASIC and QBASIC programming environments, the syntax of all BASIC statements and functions (including examples of each one), keyboard scan codes, ASCII codes, list of BASIC keywords, an extensive index, and a keyboard template on the cover. It is even spiral-bound so it lays flat while you're typing. Please let me know what you think about this article, the Quick Reference, or anything to do with BASIC programming. Ed DeJesus [70761,2303] ======================================================= Five Statement BASIC by Ed DeJesus Part 1 of 5 (of course!) When I taught Introduction to Computers a few years ago, most of the college students who took it had never seen a computer, never mind used one. So, in addition to the usual classroom material on computers, I made sure we had plenty of "hands on" sessions with a roomful of PCs the University owned. My students got to experience at least one word processing program, spreadsheet, database and (of course) game. I hoped this would give them a feel for the possible applications of PCs. I also wanted them to try out programming, since all of those applications had originated from people sitting down and writing code. But how could I do this? How dare I expect students with little or no computer experience to do any programming? The University's PCs all had BASIC on them, so that seemed like a good choice for a language. But if you've ever peeked into the BASIC manual that may have come with the BASIC on your PC, you know that BASIC contains hundreds of statements and commands. It seemed overwhelming, even to me (and I was the professor). Then I had an idea. What if I discarded all the exotic (and seldom-used) statements and concentrated on the most fundamental (and most used) statements? What were those few statements which could still do most of the things computer programs do? I thought about this for a long time. I eventually narrowed all of those many possibilities down to five essential statements. In this article, I want to show you how to write your own programs, even if you've never programmed before, with "Five Statement BASIC". (I rather like that title, by the way, because when I was in college there was a book called "Ten Statement Fortran", and BASIC is twice as easy as Fortran.) By the end we will even write a simple program that can help you balance your checkbook. 1. Introduction Every computer, my students had learned in class, can be thought of as consisting of a few related parts. You can cut the computer up in various ways, but one list of parts is: input - information we put into the computer; output - information the computer puts out to us; arithmetic - the computer can calculate with numbers; logic - the computer can decide things if they are in numerical form; memory - the computer can store and retrieve information internally; and control - the computer can control what it is going to do next. A computer program is a list of instructions to a computer. These instructions tell the computer what information we will input; how to process that information using arithmetic, logic, memory and control; and what information to output to us. Computer programs must be written in a language the computer (and the programmer) can understand. For this reason, computer languages usually consist of a small subset of English words, which the computer can translate into actions. The BASIC language is a good language to learn how to write programs in. It was first developed at Dartmouth University for that very purpose. "BASIC" is an acronym standing for "Beginner's All-purpose Symbolic Instruction Code". The "Beginner's" part suggests that this is an easy language to learn. The "All-purpose" part is also appropriate. With BASIC you can write programs that do just about anything: financial calculations, scientific computation, games, whatever. BASIC can play music. BASIC can draw pictures. Practically anything you can use your computer for can be written in BASIC. The five statements you will learn are general enough to appear in any application you might want to write in BASIC. There are a few different types of BASIC around. On your computer you may have a BASIC interpreter, such as BASIC.COM or BASICA.COM or BASICA.EXE or GWBASIC.EXE or QBASIC.EXE. Or you might have a fancy version, like QuickBASIC or TurboBASIC. I will present these five statements in a form that will work no matter which BASIC you have. Each statement will begin with a line number. In the interpreter, these line numbers are necessary and the computer processes the statements in numerical order. In QuickBASIC and the other fancy versions, the line numbers are optional and have nothing to do with the order the statements are processed in. I will assume you are using an interpreter and use line numbers. I suggest that you read this while sitting in front of your computer, with your BASIC running. That way, you can type in these statements or programs and try them out immediately. I will give instructions for running these programs, again assuming you're using an interpreter. If you're using one of the fancy versions, check your manual for how to run a program. 2. The PRINT Statement: mainly for output, with a little arithmetic Programmers could get into a big debate about which computer function (input, output, arithmetic, logic, memory or control) is most important, or which BASIC statement is most important. I personally think that, no matter what else a computer program does, it has to produce output of some kind. I don't care how fast it does arithmetic or how cleverly it does logic: if it can't tell me what the answer is, what good is it? For this reason I'm starting with the PRINT statement. The PRINT statement produces output on your monitor screen, in the form of text, that is, letters, numbers, etc. Let's try it out. First type: NEW I'm going to use the "" symbol to stand for the "Enter" or "Return" key on your keyboard. You must hit "Enter" at the end of each BASIC line. The "NEW" command tells BASIC we're starting a new program. From now on, I'll abbreviate this process of typing the word NEW and then hitting Enter by saying "Enter NEW". By the way, you can use upper-case or lower-case letters to type these programs and commands. BASIC doesn't care. Now type: 100 PRINT "Hello" The "100" is the line number. (It could be any number, like 1 or 7 or 50. I just picked 100.) This is a sample statement in BASIC. Believe it or not, it is also a complete BASIC program! To run this program type: RUN (From now on I'll abbreviate the "RUN" command by saying "Enter RUN".) The computer should print: Hello on your monitor screen. (The computer may then print Ok on the next line, also. It often does this. It's the computer's shorthand for "Okay, I'm ready for the next thing you want me to do.") If this didn't happen, enter NEW again, then carefully retype line 100, then enter RUN again. The computer is very picky about spelling and so forth. If it did work, congratulations! You have just written, and run, your first BASIC program! You may wish to stop at this point and bask in the glow of success, or call friends and brag. What this program did is this: it started with the first statement in the program, which happened to have line number 100, and executed that statement. Line 100 was a PRINT statement, so something would appear as output on the monitor screen. What appeared was whatever was in between the two double-quotation marks, in this case: Hello. You can use this form of the PRINT statement whenever you want to print out specific text. You could even use the PRINT statement as a simple word processor, if you wanted to. Let's write another program with PRINT statements. First, enter NEW. Then type: 100 PRINT "Dear Ms. Abercrombie," 200 PRINT " In re your letter of January 24th, we would" 300 PRINT "like to place an order immediately." 400 PRINT "Sincerely," 500 PRINT "J. P. Bigboss" Be sure to type all the "s and s. Now enter RUN. The complete text of this letter should appear on your monitor screen. The program started running with the lowest numbered statement (100, in this case), printed what was between the two double-quotation marks, then proceeded to execute the next lowest numbered statement and continued to the end. You might want to try your own programs with the PRINT statement now. Start by entering NEW. Then type a statement, beginning with a line number, then the word PRINT, then the first double-quotation mark, then whatever you want to be typed, then the second double-quotation mark, then "Enter". When you've typed all the statements, enter RUN. You might try programs that print: You may already have won $1,000,000 !!!! or Please enter your ATM password now or Congratulations! You made the HIGH SCORE! or whatever. This use of the PRINT statement is fairly simple and straightforward. It is used a lot in programs. But you'll notice that you don't get anything new back from the computer. It gives you back whatever you put in. How can you get the computer to actually do something? Try this next form of the PRINT statement. First enter NEW. Then type: 100 PRINT 8*7 (The * is an asterisk. It means "multiplied by" or "times". It's usually above the 8 key on your keyboard.) Then enter RUN. The computer should print: 56 on your monitor screen. Notice we did not use any double- quotation marks in this form of the PRINT statement. When we do use double-quotation marks that means, "Print what is in these double-quotation marks exactly as it appears." When we don't use them that means, "Don't print it as it appears: treat it as arithmetic to be calculated." In this case it calculated the value of 8 times 7, and printed that value. In other words, we can get the computer to do arithmetic for us using the PRINT statement! By the way, what would happen if we did put the 8*7 in double-quotation marks? Let's try it. First enter NEW. Then type: 100 PRINT "8*7" Then enter RUN. The computer should print: 8*7 on your monitor screen. Remember: with double-quotation marks, you get whatever is between them, exactly as it appears. Without double-quotation marks, you get arithmetic. So far we have learned about BASIC in general, how to use the NEW and RUN commands in BASIC, and how to use the PRINT statement to print text and do arithmetic. Next time, we'll see how the PRINT statement can do some fancier tricks. We'll also learn our second BASIC statement: the LET statement. See you then! ======================================================= Five Statement BASIC by Ed DeJesus Part 2 of 5 (of course!) Last time we learned how to write and run BASIC programs using the NEW and RUN commands. We then learned about our first BASIC statement, namely the PRINT statement. We saw how the PRINT statement can be used to print text on the screen, as well as do arithmetic for us. Let's look at some more arithmetic the PRINT statement can do. You can add (+), subtract (-), multiply (*), divide (/) and raise numbers to powers (^) with the PRINT statement. (The / is called a "slash" and is usually at the lower-right on a keyboard. The ^ is called a caret and is usually found above the 6 key.) Let's try this. First enter NEW. Then type: 100 PRINT 3+2 200 PRINT 3-2 300 PRINT 3*2 400 PRINT 3/2 500 PRINT 3^2 Then enter RUN. The computer should print on your computer screen: 5 1 6 1.5 9 These represent 3+2 (which is 5), 3-2 (which is 1), 3*2 (3 times 2, which is 6), 3/2 (3 divided by 2, which is 1.5) and 3^2 (3 raised to the power 2, or 3 squared, which is 9). You can enter even more complicated expressions also, but be careful. The computer evaluates complicated expressions in its own specific order. The computer does powers first. Then it does multiplication and division. Then it does addition and subtraction. Try this. First enter NEW. Then type: 100 PRINT 5+2^3*6/4-7 Then enter RUN. The computer should print out: 10 Why? The computer does powers first, replacing 2^3 by 8. Then it does multiplication and division, replacing 8*6/4 by 12. Then it does addition and subtraction, replacing 5+12-7 by 10. Wow, does that seem confusing! Just remember that the computer does powers first, then multiplication and division, and lastly addition and subtraction. To make sure it does things in the order you want, you can use parentheses to specify how you want things done. Try this. First enter NEW. Then type: 100 PRINT ((5+2)^3)*6/(4-7) Then enter RUN. This time the computer should print out: -686 It did the calculations in parentheses before it did other calculations. First it replaced 5+2 by 7. Then it replaced 7^3 by 343. Then it replaced 4-7 by -3. Then it multiplied 343 by 6 and divided by -3, to get -646. All these examples have used whole numbers, but you can use decimal numbers if you want to. And, as long as you're careful about the order of operations, the computer is a whiz at doing fractions! Now we know how to use the PRINT statement for printing exactly what we want (using double-quotation marks) and for doing arithmetic (without any double-quotation marks). There are several more uses for the PRINT statement, but we'll have to wait a bit before we learn them. 3. The LET or = statement: arithmetic and memory Suppose we wanted to keep track of our checking account balance. If we started out with $500 and deposited $50 into the account, we would have $550 altogether. We could do this calculation with a PRINT statement. First enter NEW, then type: 100 PRINT 500+50 Then enter RUN and the computer would obediently print: 550 on the monitor screen. Suppose we now wanted to record a withdrawal of $30. We could use another PRINT statement, and the previous result, like this: 200 PRINT 550-30 Then enter RUN and the computer would print: 520 as it should. But we would be doing all the work of keeping track of that balance, and writing a new PRINT statement each time we wanted to update it. It would be better if the computer would keep track of the balance for us. This is what the LET statement is for. Here's what we could do. First enter NEW. Then type: 100 LET balance = 500 Then enter RUN. This is an example of a LET statement. (By the way, notice the computer didn't print anything onto the screen. That's because we didn't tell it to! There are no PRINT statements in this program. Computers are nothing if not literal: they do exactly what we tell them to do, no more, no less. If we don't tell them to give us output, they won't!) The computer does three things when it executes a LET statement: First, it sets up a location in memory (in RAM, if you're familiar with that.) Second, it names that location whatever name is to the left of the = sign. This name is called a variable name, and the location is called a variable. It is called this because what is in the location can vary. Third, it puts into that location the result of whatever arithmetic is to the right of the = sign. Thus, our sample LET statement actually means this: "Let a location in memory named "balance" be set equal to the number 500." Pretty good shorthand, isn't it? Actually, you can make the LET statement even shorter. The LET statement is a little strange, because real programmers almost never use the word "LET" in the statement! The word "LET" is optional. This version of the LET statement is entirely equivalent to our previous LET statement: 100 balance = 500 It is understood that this is actually a LET statement, even though there is no LET in it. For this reason, the LET statement is sometimes called an = statement (or equals statement). From now on, I'll leave out the LET in each LET statement. I'm as lazy as any other programmer! As we mentioned before, we didn't get any output when we ran our LET statement, because there was no PRINT statement. To actually see the balance on the screen, we should include a PRINT statement. However, neither of the previous forms of the PRINT statement will work. Let's think why. We don't want to put the word "balance" between double-quotation marks, because the computer will just print the word balance, not what the variable named balance is. And we don't want to put the number 500 either, because that's what we wanted to avoid. Here's what we do. First enter NEW. Then type: 100 balance = 500 200 PRINT balance Then enter RUN. The computer should print: 500 on the monitor screen. In line 200 we are telling the computer, "Print on the screen whatever is currently in the variable named balance." Since what is currently in the variable named balance is the number 500 (which we put into the variable named balance in line 100) the computer prints out 500. This form of the PRINT statement is very useful, since we can now print out the value of any variable we wish. In fact we could make our program even fancier. First enter NEW. Then type: 100 balance = 500 200 PRINT "Your balance is" 300 PRINT balance Then enter RUN. The computer should print: Your balance is 500 on the monitor screen. Line 100 puts the number 500 into the variable named balance. Line 200 prints what is between the double-quotation marks, in this case: "Your balance is". Line 300 prints the current contents of the variable named balance, in this case, the number 500. We can make this even more fancier. Notice in the previous program each PRINT statement resulted in a different line. Could we get everything printed on the same line? Yes, we can! (That's what we philosopher/programmers call a rhetorical question.) We can have one PRINT statement print several things, if we separate the things by either a semi-colon (;) or a comma (,). If we use a semi-colon, the things appear on the same line, right next to each other. If we use a comma, the things appear on the same line, but in different columns. We generally use the semi-colon. Let's try this. First enter NEW. Then type: 100 balance = 500 200 PRINT "Your balance is";balance Then enter RUN. The computer should print: Your balance is 500 on the monitor screen. When the computer gets to line 200 it first prints what is in the double-quotation marks. Then it sees the semi-colon, stays on the same line and expects more things to be printed out right next to the previous thing. Then it prints out the current contents of the variable named balance. After that there is nothing else listed to be printed, so it stops printing. Let's go back to the LET statement. The left-hand side of the equals sign must be one variable name. But the right-hand side can be any arithmetic expression. We can thus use the LET statement to do arithmetic calculations and store the results in variables. Let's do this. First enter NEW. Then type: 100 balance = 500 200 deposit = 50 300 balance = balance + deposit 400 PRINT balance Then enter RUN. The computer should print: 550 on the monitor screen. Let's see how this works. At line 100, the computer sets up a variable named balance and puts the number 500 into that location. We've done that before. At line 200, the computer sets up another variable named deposit and puts the number 50 into that other location. (You can have as many variables as you can think up names for. Each name should start with a letter and be eight (or fewer) characters long.) At line 300, the computer takes whatever is in the variable named balance (namely, the number 500) and whatever is in the variable named deposit (namely, the number 50), and adds those two things together. It then puts the result of that addition (namely, the number 550) back into the variable named balance. The variable named balance now contains the number 550. At line 400, the contents of the variable named balance (namely, the number 550) is printed on the screen. Notice in this program that the contents of the variable named balance changes. (That is why these things are called variables!) What happened to the number 500 that used to be in the variable named balance? It's gone. It's history. We can regard this either positively or negatively. On the positive side, we can always be sure that the latest thing we put in a variable will be there, regardless of what that variable ever held before. On the negative side, we can't ever get back a number once it has been replaced in a variable. (Of course, if we yearned for that original balance of 500 we could always set up another variable to hold it. We could name the new variable origbal (short for original balance) and put 500 into it and then not change it again.) Any calculation you do with a paper and pencil or calculator, you can do with LET statements. You can balance your checkbook, calculate a mortgage, compute a course to the moon, keep track of bowling scores, convert teaspoons to milliliters, add cards in blackjack, monitor phone bills, etc. Anything you can do with numbers, you can do with a LET statement. And then print out the answer with a PRINT statement! So far we have learned about PRINT statements and LET statements. We have also used variables in our programs, which lets us do many interesting things. Next time we'll learn about how to get input into our programs using the (can you guess?) INPUT statement. See you then! ======================================================= Five Statement BASIC by Ed DeJesus Part 3 of 5 (of course!) So far we have learned how to get output from our programs, using the PRINT statement, and how to do arithmetic with variables in our programs, using the LET statement. 4. The INPUT statement: input and memory The last program we wrote was a very simple checkbook balancing program. Starting with the original balance, and knowing the amount of the deposit, the computer calculated the new balance. There's a big problem with using a program like this, however, and you may have noticed it already. Each time we run this program we have to actually change the program to change the numbers in it. Obviously this isn't the way real programs work. If you've ever used a spreadsheet program or word processor, you know you don't have to actually change the program to get it to do various things. You just change what you input to the program. That's what we want to do now. To input information into a BASIC program we use--can you guess?--an INPUT statement. Let's try this. First enter NEW, then type: 100 INPUT balance 200 PRINT balance then enter RUN. Line 100 is an INPUT statement. When the computer executes an INPUT statement, it does three things: First, it prints a question mark on the monitor screen. This let's you know that it is waiting for you to enter some input. Second, it keeps waiting until you type some input and hit the Enter key. Third, when you do enter some input it stores the input in whatever variable (or variables) you have listed after the word "INPUT" in the statement. Line 100 is therefore a shorthand telling the computer, "Wait for some input from the keyboard, and when you get the input, put it into the variable named balance." When you run this program, you should see: ? on your monitor screen. The computer is patiently waiting for input. Type any number (like 500, without the dollar sign), then hit the Enter key. The computer will put that number into the variable named balance. In line 200 the computer will print the current contents of the variable named balance on the monitor screen. If you entered the number 500, you should see: 500 on the screen. We use the INPUT statement to get data into the variables that our program uses to make calculations. Using the INPUT statement means we can write programs where some of the variables (like the balance of a checking account) don't start out with any number values, but get their values from whomever uses the program. This is just how word processors or spreadsheets or other programs get their information to their variables. One problem about the INPUT statement as we've used it is this: when that question mark appears on the screen you have no idea what the computer is looking for! For this reason, it's a good idea to precede every INPUT statement with a PRINT statement telling the user what to type. Let's do this, and input the deposit also. First enter NEW then type: 100 PRINT "Please type the original balance, then hit Enter." 200 INPUT balance 300 PRINT "Please type the deposit, then hit Enter." 400 INPUT deposit 500 balance = balance + deposit 600 PRINT "Your new balance is";balance then enter RUN. The computer will print the message in line 100 on the monitor screen. Notice several things about this message. First, it tells the user exactly what input the computer is expecting, so the user knows what should be typed. Second, it reminds the user to hit Enter, so the user doesn't sit around for a month wondering what's taking the computer so long. Third, it says, "Please", so the user knows that the programmer knows that a human being will be using this program. In line 200, the computer will wait for you to enter a number. Enter any number you wish. The computer will put that number into the variable named balance. In line 300, the computer will again print a courteous message on the screen telling the user exactly what input the computer is expecting. In line 400, the computer will again wait for you to enter a number. The computer will put whatever you enter into the variable named deposit. In line 500, the computer will add the contents of the variable named balance and the contents of the variable named deposit, and put the sum into the variable named balance. (The previous contents of the variable named balance are destroyed. Sayonara.) In line 600 the computer will print on the screen the new contents of the variable named balance. This should be the sum of the two numbers you entered. You can use similar INPUT statements to get any kind of data into a program. If there's a calculation you do all the time, you can now write a program that will input the data and do that calculation for you. Suppose you have to convert inches to centimeters a lot. Here's a program that will do it for you. First enter NEW, then type: 100 PRINT "Please type the number of inches, then hit Enter" 200 INPUT inches 300 centims = inches * 2.54 400 PRINT inches;"inches equals";centims;"centimeters." then enter RUN. In line 100 the computer will print a courteous message requesting the number of inches to be converted. In line 200 the computer will wait for you to enter a number, then put that number into a variable named inches. In line 300 the computer will multiply the number of inches by 2.54 (the approximate conversion factor) and put the result into a new variable named centims. (We can't name the new variable centimeters, as we would prefer, because that name is too long.) Line 400 is a very fancy PRINT statement: let's look at it piece by piece to see what it does. First it prints the contents of the variable named inches. Then, on the same line, and right next to the number it just printed, it prints the words "inches equals". Next, on the same line and right next to the words it just printed, it prints the contents of the variable named centims. Lastly, on the same line and right next to the number it just printed, it prints the word "centimeters" and a period. In other words, this PRINT statement fills in the blanks of a sentence. If you had entered 10 for the number of inches, it would print: 10 inches equals 25.4 centimeters. Pretty neat, huh? Programmers use PRINT statements like this one, containing variable names along with regular words between double-quotation marks, to construct sentences that make it seem as if the computer is talking to you. Combined with INPUT statements that get information from you, such PRINT statements can be part of a real conversation between you and the computer. We can take this one step further. What if you want to input a person's name, not a number, into a program? You can do this using the INPUT statement also. The only difference is in the type of variable you put the input into. You can't use a regular variable like the kind we have been using (like balance, deposit, inches or centims), because those variables are for numbers. A person's name is made of letters, not numbers. We need variables that can hold letters, not numbers. BASIC has such variables. They are called "string" variables, because they hold a "string" of symbols: letters or whatever. String variable names differ from ordinary number variable names in just one way: string variable names end with the dollar sign symbol, $. (The idea here is that the dollar sign symbol $ looks like an "S" which reminds us, and the computer, that this variable contains a string, not numbers.) Let's try this. First enter NEW, then type: 100 PRINT "Please type your name, then hit Enter." 200 INPUT name1$ 300 PRINT "Hello ";name1$ then enter RUN. In line 100, the computer prints a courteous message, asking you to type your name. In line 200, it waits for you to type something and hit Enter. When you do, it puts it into a string variable named name1$. (We use name1$, rather than name$, because NAME is a BASIC keyword reserved for the statement which changes a file's name.) Remember that the $ on the end of the variable named name1$ means that name1$ has letters in it, not numbers. In line 300, it first prints the word "Hello" and then a space. Then, on the same line and right next to the space it just printed, it prints the current contents of the string variable name1$. If I ran this program and typed my name, Ed, the computer would print on the screen: Hello Ed This is how programmers can get their programs to use your name and talk like a person talks. You can input any non-number information using string variables, such as names, addresses, favorite foods, answers to questions, etc. Using the INPUT statement and the PRINT statement we can now communicate back and forth with the computer. So far we have learned about the PRINT, LET and INPUT statements. Next time we are going to learn about two statements, GOTO and IF, which help control under what conditions the computer does certain actions. See you then! ======================================================= Five Statement BASIC by Ed DeJesus Part 4 of 5 (of course!) So far we have learned how to use the PRINT statement to print output on your monitor screen, the LET statement to do arithmetic with variables, and the INPUT statement to get input from the user into the program. 5. The GOTO statement: control Let's see how we're progressing toward our goal of a program that will help balance a checkbook. We can call both deposits and withdrawals "actions" and have our program handle them both. First enter NEW, then type: 100 PRINT "Please type original balance, then hit Enter." 200 INPUT balance 300 PRINT "Please type deposit or withdrawal (-), then Enter." 400 INPUT action 500 balance = balance + action 600 PRINT "Your new balance is";balance then enter RUN. Lines 100 and 200 request and input the original balance, as we've done before. Line 300 requests the action taken: a deposit is an ordinary number (assumed to be positive) while a withdrawal is a negative number. Line 400 inputs the deposit or withdrawal amount and puts it into a variable named action. Line 500 adds the original balance and the action and puts the result back into the variable named balance again. (Notice that if the action is a deposit, a positive number, the balance will increase (as it should), while if the action is a withdrawal, a negative number, the balance will decrease (also as it should). That's why we only need one variable, regardless of whether the action is a deposit or a withdrawal.) Line 600 prints out the new balance, as we've done before. This is a pretty good program, as far as it goes. The problem is it doesn't go far enough or, rather, long enough. What if you have several deposits? Or several withdrawals? Or some deposits and some withdrawals? You would have to run this program for each transaction, entering the balance again every time you ran it. That seems like a lot of work. And the whole idea behind computers is for us to do less work! What we would like is for us to be able to enter several transactions. In terms of the program, we would like to repeat lines 300, 400, 500 and 600 several times. We could do this by actually retyping those four lines after line 600, perhaps calling the extra versions 700, 800, 900 and 1000. Then we could at least enter two transactions each time we ran the program. But that still isn't what we would prefer. We really want lines 300 to 600 to be repeated an indefinite number of times. When line 600 is done executing, we want the program to go back to line 300 again, so we can do more transactions. BASIC has a statement for this kind of process: the GOTO statement. Let's add a GOTO statement to our program. Don't bother entering NEW, we'll just add it to the program we already have. Type: 700 GOTO 300 When the computer gets to line 700, it is directed to go to line 300, which it does. It then executes the statement at line 300 and continues on from there, just like before. The GOTO statement is a control statement. It controls what the computer does next. Ordinarily the computer just executes the statements in numerical order. When it runs out of statements, it stops. But when it hits a control statement, it is told to do something different from that temporarily. The GOTO statement is very simple. It consists of the word GOTO and then the line number of wherever you want the computer to go to in the program. There is one problem with the GOTO statement. If you haven't run this program yet, do so now. Enter RUN. If you keep entering transactions, the program just keeps running! Every time the computer gets to line 700, it goes to line 300, eventually gets to line 700, goes to line 300, gets to 700, goes to 300, to 700, to 300, 700, 300, 700, 300, 700, 300 .... In the computer world, this is called an "infinite loop". I'm sure you'll agree this is an appropriate term! The computer keeps looping around and around and around. If we didn't do something, it would keep going around forever. It's like those brooms carrying the buckets of water in The Sorcerer's Apprentice. There is something we can do to stop this infinite loop or, indeed, any BASIC program we want to stop. Hold down the Control (or Ctrl) key and while you're holding that down, hit the Break key. This combination is called Control-Break or Ctrl-Break. The program should stop running. Whew! So the GOTO statement gives us part of what we want: it lets part of the program be repeated, by jumping back to the first statement we want to be repeated. Now what we want is a way to get out of that "loop", without having to hit Ctrl-Break all the time. We need some way for the computer to decide that it is time to stop. And computer decisions mean computer logic. 6. The IF statement: logic We've all heard of "computer logic" and we may have an image of the computer deep in thought pondering the imponderables of the universe. But computers are primarily number-crunchers and any logic that they exercise is primarily concerned with numbers. In fact, the only fundamental logic the computer can do involves numbers. All a computer can do is compare one number with another, then decide if they are equal or if the first is bigger or smaller than the second. That's about it! Of course, the computer can also deal with anything you can express in terms of numbers. So by expressing letters as numbers (using the ASCII code), the computer can decide if your answer to a question is "yes" or "no". In BASIC, computer logic is done by the IF statement. Here is an example. Don't bother typing it, just look at it: 100 IF action > 0 THEN PRINT "This is a deposit." The statement starts with a line number, of course, then the word IF. After the word IF, we put the number relation we want the computer to decide on. In this case we put "action > 0" which means "action greater than zero". In other words, we are really saying, "Is the value of the variable named action greater than zero?" This is what we want the computer to decide for us. After the number relation we put the word THEN, and after that we put whatever we want the computer to do if the number relation is true. When the computer executes an IF statement, it does three things: First, it examines the number relation that we have put after the word IF and before the word THEN. The relation must be something to do with how two arithmetic expressions compare to each other. Second, it decides if the number relation is true or not. This is the logic part. Third, if the number relation is true, the computer does whatever comes after the word THEN. If the number relation is not true, the computer doesn't do anything. It just continues on with the next statement in the program. Our sample IF statement is really a shorthand for the following, "Computer, look at the number relation "action > 0". Find out if the current value of the variable named action really is greater than zero. If it is, print the message, "This is a deposit." If it isn't, never mind, just go on to the next statement." Obviously, the result of this particular IF statement depends on what happens to be in the variable named action at the moment the IF statement is executed. In our program, the value of action is input from us to the computer. In other words, with the IF statement we can have the computer do various things in a program by giving it certain input. We can control the computer program even while it is running! This is good, because it means we don't necessarily have to change the program itself to get different things to happen. All we have to do is input things into the computer, then have the computer check our input with IF statements to do various tasks. In our sample IF statement, we could use this in our program to see if our inputted action is positive (meaning a deposit) or negative (meaning a withdrawal). To find out if the action is a withdrawal we would use an IF statement like this: 100 IF action < 0 THEN PRINT "This is a withdrawal." This tells the computer to check if the value of the variable named action is less than zero, and if it is to print out an appropriate message. Of course, we already know whether it's a deposit or a withdrawal, but it is still fun to have the computer do the work. The IF statement works with any number relation. We could also have the computer check our balance. We could put an IF statement in our program something like this: 100 IF balance <= 50 THEN PRINT "Your balance is getting low!" This tells the computer to check the value of the variable named balance. If it is less than or equal to 50, the computer should print that warning message. As you can probably see, there are all kinds of uses for IF statements. Whenever you run a program (say, a word processor) where different keys do different tasks, that program has lots of IF statements to check which keys are pressed, what conditions currently exist, and what to do as a result. This is also true in games: when you say the right magic words, when you pull the right lever, when you shoot the right bad guy, IF statements are deciding what you did, what it should mean and what the result should be. As I said before, anything you can phrase in terms of number relations can be put into an IF statement. What makes the IF statement especially powerful, however, is not its logic, but what it can do if the number relation is true: the statement after the word THEN. In particular, if you put a GOTO statement after the THEN, you have a powerful statement. Why is this so powerful? Because depending on the outcome of the IF statement, the computer can go to a completely different part of the program and do many other tasks, more than would fit on the line after the word THEN. Using a GOTO with the IF statement allows you to write more useful and sophisticated programs. Using a GOTO with an IF statement is also how we will get our checkbook balancing program to stop its infinite loop. So far, this program looks like this: 100 PRINT "Please type original balance, then hit Enter." 200 INPUT balance 300 PRINT "Please type deposit or withdrawal (-), then Enter." 400 INPUT action 500 balance = balance + action 600 PRINT "Your new balance is";balance 700 GOTO 300 We will now use an IF statement to decide if it is time to stop the program. Let's think about this. When do we want the program to stop? When we have no more deposits and no more withdrawals to enter. In terms of numbers, when we have no more positive numbers and no more negative numbers to enter. Well, if we have no more positive numbers and no more negative numbers, all that is left is the number zero. In other words, if we enter the number zero as our action, that will be a signal to the computer to stop the program. To do this, we must add these lines to the existing program: 350 PRINT "Please type zero (0), then Enter, to stop." 450 IF action = 0 THEN GOTO 800 800 PRINT "All done. Goodbye!" So the entire program looks like this: 100 PRINT "Please type original balance, then hit Enter." 200 INPUT balance 300 PRINT "Please type deposit or withdrawal (-), then Enter." 350 PRINT "Please type zero (0), then Enter, to stop." 400 INPUT action 450 IF action = 0 THEN GOTO 800 500 balance = balance + action 600 PRINT "Your new balance is";balance 700 GOTO 300 800 PRINT "All done. Goodbye!" Notice that when you want to insert new lines into an existing program, you just use line numbers that are in between the lines you want to precede and follow the new statement. For instance, the new line 350 goes in between the old lines 300 and 400. That's one reason why I number my lines as multiples of 100: there's lots of room to add new lines. Though this be programming madness, yet there is method in it. Let's see what the new lines do. Line 350 prints additional instructions to the user, reminding them how to stop the program. (This line had to come before the INPUT statement it is for.) Line 450 is the new IF statement. Now if the user enters an action of 0, the computer will go to line 800. (This line 450 had to come after the INPUT statement and before the variable named action was used for something else.) Line 800 is primarily there so that the GOTO statement in line 450 has someplace to go to! (This line had to come after the GOTO statement in line 700, to be outside the infinite loop.) We should check our completed program to see if it really will behave as we want it to. Lines 100 and 200 tell the user to input the balance, then actually do the inputting. Lines 300, 350 and 400 tell the user to input the action, then actually do the inputting. Line 450 checks the action: if the action is zero, the computer jumps to line 800 and the program is over. If the action is not zero, but is some positive or negative number, the computer just goes to the next statement. Line 500 calculates the new balance and line 600 prints it out. Line 700 goes back to line 300 to get a new action. And line 800 is a message letting the user know the program is over. You now know the five most important and most used statements in BASIC. Congratulations. And congratulations again: Our checkbook-balancing program is complete! Now that you know about the PRINT, LET, INPUT, GOTO and IF statements, you probably want to write your own programs in BASIC. But how do you get started writing a program? You may also be wondering about some of the other BASIC statements available. We'll see how to write a program, and some other BASIC statements, next time. See you then! ======================================================= Five Statement BASIC by Ed DeJesus Part 5 of 5 (of course!) In the previous four parts we've learned about the five most useful BASIC statements, namely PRINT, LET, INPUT, GOTO, and IF. In fact, we have used those statements to write a simple program to help balance a checkbook. Now we want to see how to actually write a program from scratch, and what other statements are available. 7. How to write a program You now have all the basics to write programs in BASIC. You can get information into the computer, using the INPUT statement. You can get information out of the computer, using the PRINT statement. You can have the computer do calculations, using the LET or = statement. You can have the computer go to different parts of the program using the GOTO statement. And you can have the computer check various conditions numerically and do something as a result, using the IF statement. But although you may have the tools, you may feel as if you don't know what to do with them. How do you actually write a program? What do you do first? I am a professional programmer, and I have seen other programmers program, and there is no single way to go about programming. It's like writing a story. There are many approaches. You could start with a character, an action, a piece of dialogue, a place, a feeling. You could outline it first, or just write something down and expand on it. Any approach is valid if it works. In programming we can be a little more structured. Here is a list of steps you might use to write a program for yourself. It is highly subjective and intended for the beginner. I think most professional programmers would not go by this list, but that is because they have more experience and their own styles. The beginner just needs to get the program to work. Your style will come as you program. Steps to write a program: 1. Make sure you know exactly what you want your program to do, before you even start. Write down what you expect the program to do. (Many of the problems I have writing programs are not because the program doesn't work, but because the person who wanted the program didn't really know exactly what they wanted.) 2. What output do you want from the program? Is it a number, several numbers, a table of numbers? A letter, a word, a sentence? A picture? A sound? What are the outputs? When you know what the outputs are, you can write the PRINT statements to create them. Include the variables that will contain the information to be outputted. (In our checkbook-balancing program, we knew we wanted the new balance as an output, so we could have started with the statement printing that variable named balance.) 3. How will this information be arrived at? Is it a calculation? Write down the calculation. Now turn the numbers into variables and the calculation into a LET or = statement. (In our program, we knew we could calculate the new balance from the old balance and the transaction. We could make up variables for these and write our LET statements.) 4. What inputs will the computer need to do these calculations? Write down the variables that need to be input. Then write an INPUT statement for each one. Then write a PRINT statement to introduce each one, telling the user what is expected by each INPUT statement. (In our program, we would need the original balance and each action, so we would have INPUT statements for each variable and PRINT statements for each INPUT statement.) 5. Are there any groups of statements that will be repeated? If so, write GOTO statements to return to the first statement to be repeated. Remember to include a way out of each infinite loop! (In our program, we knew we would be inputting several actions, so we looped back to those statements.) 6. What decisions, checks or tests need to be made? Are there different situations where different things should be done? Are there any special conditions which require special tasks? Each of these use IF statements. Try to phrase the decision, check, test, situation or condition in terms of number relations which can be used in an IF statement. If what is to be done is simple, put it on the same line, after the word THEN. If it is complicated, use a GOTO to jump to a different part of the program. (In our program, stopping the program was a special condition. Or checking the transaction or the balance would also require an IF statement.) 7. When you have a completed program that doesn't work, go through each statement as if you were the computer. Forget what you want it to do: first, see what it is doing. Remember the computer is very picky and very literal. When you see the place where what you have written is not doing what you want, figure out why. When you understand that, then figure out how to get it to do what you want. 8. Use whatever help you have available: this and other articles, manuals, examples. Don't forget people: experienced programmers are used to thinking like a computer does, and can often find and correct problems very quickly. Just ask! 8. Extras In this article I have only presented five BASIC statements. There are many more. I have also told you about only two BASIC commands: NEW and RUN. Here are some more of the BASIC commands and statements. (The commands are only for BASIC interpreters. If you're using something fancy (like QuickBASIC or TurboBASIC, check your manual for how to do the same thing.) You'll have to look up the details in your manuals, but this should whet your appetite: 1) The SAVE command: Are you getting tired of retyping these programs over and over? Well, you can save every program you type into a file on your floppy or hard disk, then load it back whenever you want to change or run it. Suppose I wanted to call our sample program CHEKBOOK. (I'm not really that lousy at spelling: remember, the file name can't be longer than eight characters, so I can't call it CHECKBOOK). I would then type: save "chekbook.bas",a Here's what this does. First, you don't need a line number: this is a command (like NEW or RUN), not a statement. The word "save" tells the computer to save the current program in a file. Whatever is in double-quotation marks is the filename and extension of the file. The filename starts with a letter and is eight (or fewer) characters long. The .bas is the standard "extension" (last name) of files written in BASIC. The ",a" means to save the program in standard ASCII form. This way you can look at the program (and even edit it) using other programs. If you don't use the ",a" it gets saved in a special BASIC-only format that looks like gibberish to mere mortals, but BASIC understands it. 2) The LOAD command: Any program that has a .bas extension (last name) can be loaded as the current program, then changed or run or renamed or whatever. If I saved our program as chekbook.bas, I would type: load "checkbook.bas" This finds the program in the current directory, and loads it as the current program. WARNING: if you were working on another program, loading a new program wipes out the one you were working on. Save the first program before loading another one. 3) The LPRINT statement: If you would like your program to print output on the printer (which seems reasonable), rather than on the monitor screen, use the LPRINT statement instead of the PRINT statement. LPRINT is short for "line printer", which is what printers used to be in the olden days. LPRINT works exactly the same as a PRINT statement does. If you use LPRINT, don't expect to see the results on the screen! 4) The FOR and NEXT statements: If you want to repeat a group of statements a specific number of times, it can be clumsy to use GOTOs and IFs. The FOR and NEXT statements are specifically for this use. Suppose you want to repeat a group of statements 5 times. Use this: 100 FOR i = 1 to 5 [group of statements to be repeated] 800 NEXT i The FOR and NEXT statements say, "Set up a variable named i. Give it the value of 1. Execute all the statements up until the NEXT statement. When you get to the NEXT statement, check to see if i is more than 5 yet. If it is, we're done with this loop, so go to the statement after the NEXT statement. If i isn't more than 5, increase i, do the loop, and check again." You can use any variable for the counter, it doesn't have to be named i. And you can use that counter variable inside the loop. Try out some FOR ... NEXT loops to see how they work. You might try generating the squares and cubes of the numbers from 1 to 10. 5) The IF ... THEN ... ELSE statement: You know about the IF statement already. This is a modification of it. This handles the situation where you want to do one thing if the number relation is true and something else if it isn't. Here's an example: 100 IF x > 0 THEN PRINT "Positive" ELSE PRINT "Not positive" As before, if the number relation is true (in this case, if x is greater than zero), the computer does the statement which comes after the word THEN. (In this case, if x is greater than zero, it will print the word "Positive".) The new part is the ELSE. If the number relation is not true (in this case, if x is zero or a negative number), the computer does the statement which comes after the word ELSE. (In this case, if x is not greater than zero, it will print out, "Not positive".) As before, you can use GOTO statements for the statement after the word THEN or after the word ELSE. This lets the IF statement make more complicated decisions. 6) Mathematical functions: Besides addition, subtraction, multiplication , division and powers, BASIC can do all sorts of other mathematics also. You can do trigonometry (cos(x), sin(x), tan(x)), inverse trigonometry (atn(x)), logarithms (log(x), ln(x)), square roots (sqr(x)) and many other functions. Use these in arithmetic expressions and with variables just as you do any other calculation. Here's an example: 100 s = 2 * sin(x) 7) The LOCATE statement: If you want output from PRINT statements to appear at certain places on the screen, use the LOCATE statement before each PRINT statement. It tells the computer which vertical row and which horizontal column to begin the next print statement on. For instance: 100 LOCATE 1,1 200 PRINT "Hello!" will print "Hello!" in the upper left-hand corner (row 1, column 1). By comparison: 100 LOCATE 1,37 200 PRINT "Hello!" will print "Hello!" at the top center (row 1, column 37). You can use variables for the row and column also. This can be used for special output screens, games and animation. 8) Sound: You can use BASIC to produce sounds through your computer's speaker. To do this you use the BEEP, PLAY or SOUND statements. I refer you to the manual for details. 9) Graphics: If your monitor is a graphics monitor, you can use BASIC to draw graphics on the screen. To do this you use the SCREEN and COLOR statements to set up the screen, and the CIRCLE, LINE, PSET, DRAW and PAINT statements to make the graphics. You can use the GET and PUT statements to save and load pictures in variable arrays. Again, I refer you to the manual for details. 10) Comments: It's a good idea to add descriptive comments to your programs, to remind yourself and others what variables mean, what certain parts of the program do, etc. You do this by using the single-quotation mark (') to mark the beginning of a comment. Here's an example: 100 INPUT balance 200 ' the variable balance represents the current balance Line 200 doesn't do anything. It's just there so that eight months from now when you look at this program you'll know what you meant by the variable named balance. By now you've probably gotten some ideas about programs you'd like to try writing. You've also gotten enough experience with some BASIC statements to make sense of some of the manuals. Good luck with your programming! And have fun! =======================================================